package com.sun.javaalgorithm.day01;

/**
 * @version 1.0
 * @Package: com.sun.javaalgorithm.day01
 * @ClassName: Leetcode01
 * @Author: sgq
 * @Date: 2024/4/10 15:08
 * @Description: TODD
 */
public class Leetcode01 {

    /**
     * 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
     *
     * 请必须使用时间复杂度为 O(log n) 的算法。
     * @param nums
     * @param target
     * @return
     */
    public static int searchInsert(int[] nums, int target) {
        int i=0,j=nums.length-1;
        while (i<=j){
            int mid=(i+j)>>>1;
            if(nums[mid]>target){
                j=mid-1;
            }else if(nums[mid]<target){
                i=mid+1;
            }else{
                return mid;
            }
        }
        return i;
    }


    /**
     * leftmost（基础版本改进）
     * @param nums
     * @param target
     * @return
     */
    public static int searchInsert2(int[] nums, int target) {
        int i=0,j=nums.length-1;
        while (i<=j){
            int mid=(i+j)>>>1;
            if(nums[mid]>=target){
                j=mid-1;
            }else{
                i=mid+1;
            }
        }
        return i;
    }

    public static void main(String[] args) {
        int[] nums={1,2,3,5,6};
        System.out.println(searchInsert(nums,2));
        System.out.println(searchInsert(nums,5));
        System.out.println(searchInsert(nums,6));
        System.out.println(searchInsert(nums,7));
        System.out.println(searchInsert(nums,4));
        System.out.println(searchInsert(nums,0));

        System.out.println(searchInsert2(nums,2));
        System.out.println(searchInsert2(nums,5));
        System.out.println(searchInsert2(nums,6));
        System.out.println(searchInsert2(nums,7));
        System.out.println(searchInsert2(nums,4));
        System.out.println(searchInsert2(nums,0));
    }
}
